﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class BUserM : INTPage
{
    public int rowNo = 0;
    SqlHelp help = new SqlHelp();
    UserDAO comm = new UserDAO();
    UserModel model = new UserModel();
    CommonMethod comHelp = new CommonMethod();

    protected void Page_Load(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl2);
        if (!IsPostBack)
        {
            //权限
            comHelp.GetRight(this, new string[] { Session["UserCode"].ToString(), Session["CoCode"].ToString(), "BUser" }, gvUsers, new string[] { "cmdAdd", "cmdEdit", "12cmdAdd12" }, new int[] { 11, 12 }, CommonModel.loginOut2);
            ViewState["SortOrder"] = "UserCode";
            ViewState["OrderDire"] = "DESC";
            bindGV("");
        }
    }
    //绑定用户
    public void bindGV(string selectSql)
    {
        DataTable dt = comm.GetUserInfo(selectSql);
        string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
        DataView view = dt.DefaultView;
        view.Sort = sort;
        gvUsers.DataSource = view;
        gvUsers.DataBind();
        if (view.Count > 0)
        {
            // 设置分页行永远显示
            gvUsers.BottomPagerRow.Visible = true;
            //赋值Label记录条数
            Label label1 = gvUsers.BottomPagerRow.FindControl("lblCount") as Label;
            label1.Text = view.Count.ToString();
        }
    }
   
    // 添加
    protected void cmdAdd_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl2);
        //model = null;
        model.UserCode = txtCode.Text.Trim().ToString();
        model.UserName = txtLogin.Text.Trim().ToString();
        model.UserEngName = txtEname.Text.Trim().ToString();
        model.UserFullName= txtName.Text.Trim().ToString();
        model.UserPwd = Login.EncryptPassword(txtPwd.Text.Trim(), Login.PasswordType.MD5);
        model.Email = txtEmail.Text.Trim().ToString();
        model.BackupEmail = txtBackupEmail.Text.Trim().ToString();
        model.UserPost = txtLevel.Text.Trim().ToString();
        model.LawEntity = txtLegal.Text.Trim().ToString();
        model.DomainName = txtDomain.Text.Trim().ToString();   
        model.DeleteFlag = ddlStatus.SelectedValue;    

        model.AddAuthor = Session["UserCode"].ToString();
        model.date = System.DateTime.Now.ToString("yyyy-MM-dd hh:mm");

        if (comm.AddUser(model) > 0)
        {
            txtLogin.Text = "";
            bindGV("");
            CommonMethod.regAlertMessage("操作成功-Success!", this);
        }
        else
        {
            CommonMethod.regAlertMessage("出现错误-Error!", this);
        }
    }
    // 编辑
    protected void cmdEdit_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl2);
        //model = null;
        model.UserCode = txtCode.Text.Trim().ToString();
        model.UserName = txtLogin.Text.Trim().ToString();
        model.UserEngName = txtEname.Text.Trim().ToString();
        model.UserFullName = txtName.Text.Trim().ToString();
        //model.UserPwd = Common.EncryptPassword(txtPwd.Text.Trim(), Common.PasswordType.MD5);
        model.Email = txtEmail.Text.Trim().ToString();
        model.BackupEmail = txtBackupEmail.Text.Trim().ToString();
        model.UserPost = txtLevel.Text.Trim().ToString();
        model.LawEntity = txtLegal.Text.Trim().ToString();
        model.DomainName = txtDomain.Text.Trim().ToString();
        model.DeleteFlag = ddlStatus.SelectedValue;

        model.UpdateAuthor = Session["UserCode"].ToString();
        model.date = System.DateTime.Now.ToString("yyyy-MM-dd hh:mm");

        if (comm.EditUser(model) > 0)
        {
            txtLogin.Text = "";
            setFlag(true);
            bindGV("");
            CommonMethod.regAlertMessage("操作成功-Success!", this);
        }
        else
        {
            CommonMethod.regAlertMessage("出现错误-Error!", this);
        }
    }

    private void setFlag(bool Flag)
    {
        bool Flag1 = false;
        if (Flag == true)
        {
            Flag1 = false;
        }
        else
        {
            Flag1 = true;
        }
        txtCode.Enabled = Flag;
        cmdAdd.Enabled = Flag;
        cmdEdit.Enabled = Flag1;
    }
    // Gridview换页
    protected void gvUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            gvUsers.PageIndex = e.NewPageIndex;
            btnSelect_Click(sender, e);//数据绑定
        }
        catch
        {
        }
    }
    // GrivdView 行事件
    protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        rowNo++;
        //鼠标经过事件
        if (e.Row.RowIndex != -1)
        {

            //设置悬浮鼠标指针形状为"小手"
            e.Row.Attributes["style"] = "Cursor:hand";
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string flag = e.Row.Cells[7].Text;
                if (flag.Equals("1"))
                {
                    e.Row.Cells[7].Text = "停用-Inactive";
                }
                else
                {
                    e.Row.Cells[7].Text = "启用-Active";
                }
                e.Row.Attributes.Add("onmouseover", "lastColor=this.style.backgroundColor;this.style.backgroundColor='#CCCC99';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=lastColor;");
                if ("zh-cn".Equals(Session["Language"].ToString()))
                {
                    ((LinkButton)e.Row.Cells[11].Controls[0]).Attributes.Add("onclick", "return confirm('确实要删除此用户？');");
                    ((LinkButton)e.Row.Cells[12].Controls[0]).Attributes.Add("onclick", "return confirm('确实要重置密码？');");
                }
                else
                {
                    ((LinkButton)e.Row.Cells[11].Controls[0]).Attributes.Add("onclick", "return confirm('OK to delete?');");
                    ((LinkButton)e.Row.Cells[12].Controls[0]).Attributes.Add("onclick", "return confirm('OK to reset password?');");
                }
            }
        }
    }
    // 删除用户
    protected void gvUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl2);
        //model = null;
        model.UserCode = gvUsers.Rows[e.RowIndex].Cells[1].Text.ToString();

        if (comm.DeleteUser(model) > 0)
        {
            setFlag(true);
            CommonMethod.regAlertMessage("操作成功-Success!", this);
            txtLogin.Text = "";
            txtName.Text = "";
            txtCode.Text = "";
            txtEname.Text = "";
            txtPwd.Text = "";
            txtSure.Text = "";
            txtEmail.Text = "";
            txtLevel.Text = "";
            txtLegal.Text = "";
            txtDomain.Text = "";
            txtBackupEmail.Text = "";
            ddlStatus.SelectedIndex = 0;
            bindGV("");
            txtCode.Focus();
            CommonMethod.regAlertMessage("操作成功-Success!", this);
        }
        else
        {
            CommonMethod.regAlertMessage("无法删除-Unrecoverable Delete!", this);
        }
    }
    // GridView 编辑绑定
    protected void gvUsers_SelectedIndexChanged(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl2);
        try
        {
            string userCode = gvUsers.Rows[gvUsers.SelectedIndex].Cells[1].Text.ToString();
            DataTable dt = comm.GetOneUserInfo(userCode);
            txtCode.Text = userCode;
            txtLogin.Text = dt.Rows[0]["UserName"].ToString();
            txtEname.Text = dt.Rows[0]["UserEngName"].ToString();
            txtName.Text = dt.Rows[0]["UserFullName"].ToString();
            txtLevel.Text = dt.Rows[0]["UserPost"].ToString();
            txtLegal.Text = dt.Rows[0]["LawEntity"].ToString();
            txtEmail.Text = dt.Rows[0]["Email"].ToString();
            txtDomain.Text = dt.Rows[0]["DomainName"].ToString();
            txtBackupEmail.Text = dt.Rows[0]["BackupEmail"].ToString();
            string aa = dt.Rows[0]["deleteFlag"].ToString();
            if (!string.IsNullOrEmpty(aa))
            {
                ddlStatus.SelectedIndex = Convert.ToInt16(aa);
            }
            setFlag(false);
        }
        catch
        {     }
    }
    // 重置密码
    protected void gvUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        if (comm.updatePWD(gvUsers.Rows[e.NewEditIndex].Cells[1].Text.ToString().Trim()) > 0)
        {
            CommonMethod.regAlertMessage("密码重置成功-Success!", this);
            Response.Redirect("BUserM.aspx");
        }
        else
        {
            CommonMethod.regAlertMessage("密码重置失败-Failed!", this);
        }
    }

    // 查询
    protected void btnSelect_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this);
        string selectSql = string.Empty;
        string userNo = CommonMethod.ConvertSql(txtCode.Text.Trim().ToString());
        string loginName = CommonMethod.ConvertSql(txtLogin.Text.Trim().ToString());
        string fullName = CommonMethod.ConvertSql(txtName.Text.Trim().ToString());
        string englishName = CommonMethod.ConvertSql(txtEname.Text.Trim().ToString());
        string title = CommonMethod.ConvertSql(txtLevel.Text.Trim().ToString());
        string legalEntity = CommonMethod.ConvertSql(txtLegal.Text.Trim().ToString());
        string domain = CommonMethod.ConvertSql(txtDomain.Text.Trim().ToString());
        string email = CommonMethod.ConvertSql(txtEmail.Text.Trim().ToString());
        if (!string.IsNullOrEmpty(userNo))
        {
            selectSql = "and UserCode like '%" + userNo + "%' ";
        }
        if (!string.IsNullOrEmpty(loginName))
        {
            selectSql += "and UserName like '%" + loginName + "%' ";
        }
        if (!string.IsNullOrEmpty(fullName))
        {
            selectSql += "and UserFullName like '%" + fullName + "%' ";
        }
        if (!string.IsNullOrEmpty(englishName))
        {
            selectSql += "and UserEngName like '%" + englishName + "%' ";
        }
        if (!string.IsNullOrEmpty(title))
        {
            selectSql += "and UserPost like '%" + title + "%' ";
        }
        if (!string.IsNullOrEmpty(legalEntity))
        {
            selectSql += "and LawEntity like '%" + legalEntity + "%' ";
        }
        if (!string.IsNullOrEmpty(domain))
        {
            selectSql += "and DomainName like '%" + domain + "%' ";
        }
        bindGV(selectSql);
    }
    // 排序
    protected void gvUsers_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sPage = e.SortExpression;
        if (sPage == "UserCode")
        {
            ViewState["SortOrder"] = "UserCode";
            if (ViewState["OrderDire"].ToString() == "Desc")
                ViewState["OrderDire"] = "ASC";
            else
                ViewState["OrderDire"] = "Desc";
        }
        else if (sPage == "username")
        {
            ViewState["SortOrder"] = "username";
            if (ViewState["OrderDire"].ToString() == "Desc")
                ViewState["OrderDire"] = "ASC";
            else
                ViewState["OrderDire"] = "Desc";
        }
        else if (sPage == "USERFULLNAME")
        {
            ViewState["SortOrder"] = "USERFULLNAME";
            if (ViewState["OrderDire"].ToString() == "Desc")
                ViewState["OrderDire"] = "ASC";
            else
                ViewState["OrderDire"] = "Desc";
        }
        else if (sPage == "departname")
        {
            ViewState["SortOrder"] = "departname";
            if (ViewState["OrderDire"].ToString() == "Desc")
                ViewState["OrderDire"] = "ASC";
            else
                ViewState["OrderDire"] = "Desc";
        }
        else
        {
            ViewState["SortOrder"] = e.SortExpression;
        }
        bindGV("");
    }
    // 重置
    protected void cmdClear_ServerClick(object sender, EventArgs e)
    {
        txtCode.Text = "";
        txtLogin.Text = "";
        txtName.Text = "";
        txtLevel.Text = "";
        txtLegal.Text = "";
        txtEmail.Text = "";
        txtBackupEmail.Text = "";
        txtEname.Text = "";
        setFlag(true);
    }
    //跳页
    protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "NewPage")
            {
                TextBox tb = gvUsers.BottomPagerRow.FindControl("txtNewPageIndex") as TextBox;
                int pageindex = Convert.ToInt32(tb.Text);
                gvUsers.PageIndex = pageindex - 1;
                btnSelect_Click(sender, e);//数据绑定
            }
        }
        catch
        {
            CommonMethod.regAlertMessage("输入不合法-Error format!", this);
        }
    }

    //导出excel
    protected void cmdExport_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl2);
        try
        {            
            string selectSql = string.Empty;
            string userNo = CommonMethod.ConvertSql(txtCode.Text.Trim().ToString());
            string loginName = CommonMethod.ConvertSql(txtLogin.Text.Trim().ToString());
            string fullName = CommonMethod.ConvertSql(txtName.Text.Trim().ToString());
            string englishName = CommonMethod.ConvertSql(txtEname.Text.Trim().ToString());
            string title = CommonMethod.ConvertSql(txtLevel.Text.Trim().ToString());
            string legalEntity = CommonMethod.ConvertSql(txtLegal.Text.Trim().ToString());
            string domain = CommonMethod.ConvertSql(txtDomain.Text.Trim().ToString());
            string email = CommonMethod.ConvertSql(txtEmail.Text.Trim().ToString());
            if (!string.IsNullOrEmpty(userNo))
            {
                selectSql = "and UserCode like '%" + userNo + "%' ";
            }
            if (!string.IsNullOrEmpty(loginName))
            {
                selectSql += "and UserName like '%" + loginName + "%' ";
            }
            if (!string.IsNullOrEmpty(fullName))
            {
                selectSql += "and UserFullName like '%" + fullName + "%' ";
            }
            if (!string.IsNullOrEmpty(englishName))
            {
                selectSql += "and UserEngName like '%" + englishName + "%' ";
            }
            if (!string.IsNullOrEmpty(title))
            {
                selectSql += "and UserPost like '%" + title + "%' ";
            }
            if (!string.IsNullOrEmpty(legalEntity))
            {
                selectSql += "and LawEntity like '%" + legalEntity + "%' ";
            }
            if (!string.IsNullOrEmpty(domain))
            {
                selectSql += "and DomainName like '%" + domain + "%' ";
            }

            DataTable dt = comm.GetExcelUserInfo(selectSql);
            CreateExcel(ref dt, "UserInfo", "UserInfo");
            dt.Dispose();
            dt = null;
        }
        catch
        {
        }
    }

    //创建EXCEL
    public void CreateExcel(ref DataTable dt, string FileName, string title)
    {
        try
        {
            HttpResponse resp;
            resp = Page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName + ".xls");
            int i = 0;
            string[] colheader ={ "NO.", "员工编号", "用户名", "英文名", "中文名", "使用状态", "Email" };
            DataRow[] myRow = dt.Select("");
            StringBuilder htmlTable = new StringBuilder();
            int colcount = dt.Columns.Count;
            htmlTable.Append("<html>");
            htmlTable.Append("<table style='border-color:Black;' border='1px'>");     //添加表格   
            htmlTable.Append("<tr>");
            for (int hcount = 0; hcount < colheader.Length; hcount++)
            {
                htmlTable.Append("<td align='center' style='font-size:12px;font-weight:bolder;font-family:宋体'>" + colheader[hcount]);
                htmlTable.Append("</td>");
            }
            htmlTable.Append("</tr>");
            int rowNumber = 0;

            foreach (DataRow row in myRow)
            {
                rowNumber++;
                htmlTable.Append("<tr>");
                htmlTable.Append("<td align='center' style='font-size:12px;font-weight:lighter;font-family:宋体'>" + Convert.ToString(rowNumber) + "</td>");
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName.Equals("BankAccount"))
                    { htmlTable.Append("<td align='left' style='font-size:12px;font-weight:lighter;font-family:宋体;vnd.ms-excel.numberformat:@\'>" + row[i].ToString()); }
                    else
                    { htmlTable.Append("<td align='left' style='font-size:12px;font-weight:lighter;font-family:宋体'>" + row[i].ToString()); }
                    htmlTable.Append("</td>");
                }
                htmlTable.Append("</tr>");
            }
            htmlTable.Append("</table>");
            htmlTable.Append("</html>");
            resp.Write(Convert.ToString(htmlTable));
            //写缓冲区中的数据到HTTP头文件中 
            resp.End();
        }
        catch { }
    }
}
